package jsyf.oa.service.crm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.oa.dao.crm.EquipmentBrandDao;
import jsyf.oa.dao.crm.ExhibitionAimsDao;
import jsyf.oa.dao.crm.ExhibitionDao;
import jsyf.oa.dao.system.CompanyDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.entity.crm.ExhibitionAimsEntity;
import jsyf.oa.entity.crm.ExhibitionCusInfo;
import jsyf.oa.entity.crm.ExhibitionEntity;
import jsyf.oa.entity.system.CompanyEntity;
import jsyf.oa.facade.crm.ExhibitionFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by WHH-PC on 2017/12/24.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ExhibitionService implements ExhibitionFacade {

    @Autowired
    private ExhibitionDao exhibitionDao;
    @Autowired
    private ExhibitionAimsDao exhibitionAimsDao;

    @Autowired
    private UserDao userDao;
    @Autowired
    private EquipmentBrandDao equipmentBrandDao;
    @Autowired
    private CompanyDao companyDao;

    @Override
    public String save(String jsonData) {
        jsonData = jsonData.replace("YYY", " ");

        ExhibitionEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), ExhibitionEntity.class);
        String name = entity.getCompanyName() + equipmentBrandDao.getJSONById(entity.getBrandId()).get("name");
        entity.setName(name);
        entity.setRegionId(entity.getCity());
        String exhibitionDate = entity.getYear() + "-" + entity.getMonth();
        if (!StringUtils.isEmpty(entity.getDay())) {
            exhibitionDate += "-" + entity.getDay();
        }
        entity.setExhibitionDate(exhibitionDate);

        if (entity.getId().equals("0")) {
            //添加展会信息
            exhibitionDao.add(entity);
        } else {
            //修改展会信息
            entity.setCreateTime(null);
            exhibitionDao.update(entity);
            //删除展会小区目标
            StringBuffer conditionA = new StringBuffer();
            String[] sqlArgs = new String[1];
            if (!StringUtils.isEmpty(entity.getId())) {
                StringBuilder sb = new StringBuilder();
                sb.append(" AND REGION_ID IN (");
                entity.getAimsList().forEach(exhibitionAimsEntity -> {
                    if (entity.getIsBigAreaManager().equals("1") && exhibitionAimsEntity.getParentId().equals("0"))
                        return;
                    sb.append("'");
                    sb.append(exhibitionAimsEntity.getRegionId());
                    sb.append("',");
                });
                sb.append(") ");

                conditionA.append(" AND EXHIBITION_ID=? ");
                conditionA.append(sb.toString().replace(",)", ")"));
                sqlArgs[0] = entity.getId();
                exhibitionAimsDao.removeByCondition(conditionA.toString(), sqlArgs);
            }
        }
        //添加展会目标
        for (int i = 0; i < entity.getAimsList().size(); i++) {
            ExhibitionAimsEntity exhibitionAimsEntity = entity.getAimsList().get(i);
            exhibitionAimsEntity.setExhibitionId(entity.getId());
            if (entity.getIsBigAreaManager().equals("0")) {
                //销售管理经理只添加大区目标
                exhibitionAimsDao.add(exhibitionAimsEntity);
            } else if (entity.getIsBigAreaManager().equals("1") && !exhibitionAimsEntity.getParentId().equals("0")) {
                //大区经理只添加小区目标
                exhibitionAimsDao.add(exhibitionAimsEntity);
            }
        }
        return entity.getId();
    }

    @Override
    public JSONObject getExihibitionList(JSONObject obj) {
        String userId = obj.getString("userId");
        Integer pageIndex = Integer.parseInt(obj.getString("pageIndex") == null ? "1" : obj.getString("pageIndex"));
        Integer pageSize = 1000;
        String companyId = obj.getString("companyId");
        String brandId = obj.getString("brandId");
        String monthKey = obj.getString("monthKey");
        String exhibitionType = obj.getString("exhibitionType");

        StringBuffer condition = new StringBuffer();
        String sqlCount = "";
        JSONObject jsonUser = userDao.getViewJSONById(userId);
        if (StringUtils.isNotEmpty(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA"))
            condition.append(" AND companyId= '" + companyId + "'");
        if (StringUtils.isNotEmpty(brandId))
            condition.append(" AND brandId='" + brandId + "' ");
        if (StringUtils.isNotEmpty(exhibitionType))
            condition.append(" AND type='" + exhibitionType + "' ");
        if (StringUtils.isNotEmpty(monthKey))
            condition.append("  AND exhibitionDate LIKE '%-" + monthKey + "-%' ");
        sqlCount = condition.toString();
        //condition.append("order by DATE_FORMAT(a.EXHIBITION_DATE,' %Y-%m-%d') ");
        condition.append("limit ");
        condition.append((pageIndex - 1) * pageSize);
        condition.append(",");
        condition.append(pageSize);
        List<JSONObject> records = this.exhibitionDao.getExihibitionList(condition.toString());
        Integer recordCount = this.exhibitionDao.getExihibitionListCount(sqlCount);

//        records.forEach(e -> {
//            String exhibitionDate = e.get("exhibitionDate").toString();
//            e.put("exDateSort", fmtExhibitionDate(exhibitionDate));
//        });
//        records.sort((s2, s1) -> Integer.parseInt(s1.get("exDateSort").toString()) - (Integer.parseInt(s2.get("exDateSort").toString())));
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", records);
        objResult.put("recordCount", recordCount);
        objResult.put("pageIndex", pageIndex);
        objResult.put("pageCount", (int) Math.ceil((double) recordCount / pageSize));
        return objResult;
    }

    private Integer fmtExhibitionDate(String exhibitionDate) {
        String[] date = exhibitionDate.split("-");
        String strDate = "00000000";
        if (date.length == 1) {
            strDate = date[0] + "0000";
        } else if (date.length == 2) {
            if (date[1].trim().length() == 1)
                date[1] = "0" + date[1];
            strDate = date[0] + date[1] + "00";
        } else if (date.length == 3) {
            if (date[1].trim().length() == 1)
                date[1] = "0" + date[1];
            if (date[2].trim().length() == 1)
                date[2] = "0" + date[2];
            strDate = date[0] + date[1] + date[2];
        }

        return Integer.parseInt(strDate);
    }

    @Override
    public JSONObject getById(String id) {
        JSONObject jsonObject = new JSONObject();
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!com.alibaba.dubbo.common.utils.StringUtils.isEmpty(id)) {
            condition.append(" AND EXHIBITION_ID=? ");
            sqlArgs.add(id);
        }
        List<JSONObject> aimsList = exhibitionAimsDao.getJSONListByCondition(condition.toString(), sqlArgs.toArray());
        JSONObject exhibition = exhibitionDao.getExihibitionList(" AND id='" + id + "'").get(0);
        jsonObject.put("exhibition", exhibition);
        jsonObject.put("aimsList", aimsList);

        return jsonObject;
    }

    @Override
    public List<JSONObject> getReportData(String userId, String exhibitionId) {
        JSONObject jsonUser = userDao.getViewJSONById(userId);

        if (jsonUser != null && jsonUser.get("companyId").equals("201712161613432EAF27DBCCB7D0E6CA")) {
            JSONObject json = exhibitionDao.getExhibitionDescLimit1();
            if (json != null) {
                userId = json.get("CREATE_USER_ID").toString();
                exhibitionId = json.get("ID").toString();
            }
        }

        Map<String, JSONObject> map = exhibitionDao.getRegion2ManagerMap();
        Map<String, ExhibitionCusInfo> exhibitionCustomMap = getExhibitionCustomMap(exhibitionId);
        Map<String, JSONObject> mapAims = exhibitionDao.getExhibitionAimsMap(exhibitionId);
        List<JSONObject> regionList = exhibitionDao.getRegionByUserId(userId);
        JSONObject objectTemp;
        for (int i = 0; i < regionList.size(); i++) {
            String regionId = regionList.get(i).get("ID").toString();
            if (map.containsKey(regionId)) {
                regionList.get(i).put("userName", map.get(regionId).get("USERNAME"));
                regionList.get(i).put("userId", map.get(regionId).get("USERID"));
            } else {
                regionList.get(i).put("userName", "");
                regionList.get(i).put("userId", "");
            }

            if (mapAims.containsKey(regionId)) {
                regionList.get(i).put("customNum", mapAims.get(regionId).get("customNum"));
                regionList.get(i).put("depositNum", mapAims.get(regionId).get("depositNum"));
            } else {
                regionList.get(i).put("customNum", "0");
                regionList.get(i).put("depositNum", "0");
            }
            if (exhibitionCustomMap.containsKey(regionId)) {
                regionList.get(i).put("deposit1", exhibitionCustomMap.get(regionId).getDeposit1());
                regionList.get(i).put("deposit2", exhibitionCustomMap.get(regionId).getDeposit2());
                regionList.get(i).put("deposit3", exhibitionCustomMap.get(regionId).getDeposit3());
                regionList.get(i).put("deposit4", exhibitionCustomMap.get(regionId).getDeposit4());
                regionList.get(i).put("participationNum", exhibitionCustomMap.get(regionId).getParticipationNum());
            } else {
                regionList.get(i).put("deposit1", 0);
                regionList.get(i).put("deposit2", 0);
                regionList.get(i).put("deposit3", 0);
                regionList.get(i).put("deposit4", 0);
                regionList.get(i).put("participationNum", 0);
            }

            for (int j = i + 1; j < regionList.size(); j++) {
                if (regionList.get(i).get("ID").equals(regionList.get(j).get("PARENTID"))) {
                    objectTemp = regionList.get(j);
                    regionList.remove(j);
                    regionList.add(i + 1, objectTemp);
                }
            }
        }

        ExhibitionCusInfo exhibitionCusInfo = new ExhibitionCusInfo();
        Integer bigAreaIndex = 0;
        for (int i = 0; i < regionList.size(); i++) {
            Integer participationNum = Integer.parseInt(regionList.get(i).get("participationNum").toString());
            Integer deposit1 = Integer.parseInt(regionList.get(i).get("deposit1").toString());
            Integer deposit2 = Integer.parseInt(regionList.get(i).get("deposit2").toString());
            Integer deposit3 = Integer.parseInt(regionList.get(i).get("deposit3").toString());
            Integer deposit4 = Integer.parseInt(regionList.get(i).get("deposit4").toString());
            exhibitionCusInfo.setParticipationNum(exhibitionCusInfo.getParticipationNum() + participationNum);
            exhibitionCusInfo.setDeposit1(exhibitionCusInfo.getDeposit1() + deposit1);
            exhibitionCusInfo.setDeposit2(exhibitionCusInfo.getDeposit2() + deposit2);
            exhibitionCusInfo.setDeposit3(exhibitionCusInfo.getDeposit3() + deposit3);
            exhibitionCusInfo.setDeposit4(exhibitionCusInfo.getDeposit4() + deposit4);

            String parentId = regionList.get(i).get("PARENTID").toString();
            if (parentId.equals("0") && i > 0 || i == regionList.size() - 1) {
                regionList.get(bigAreaIndex).put("participationNum", exhibitionCusInfo.getParticipationNum());
                regionList.get(bigAreaIndex).put("deposit1", exhibitionCusInfo.getDeposit1());
                regionList.get(bigAreaIndex).put("deposit2", exhibitionCusInfo.getDeposit2());
                regionList.get(bigAreaIndex).put("deposit3", exhibitionCusInfo.getDeposit3());
                regionList.get(bigAreaIndex).put("deposit4", exhibitionCusInfo.getDeposit4());
                bigAreaIndex = i;
                exhibitionCusInfo = new ExhibitionCusInfo();
                continue;
            }
        }

        return regionList;
    }

    public Map<String, ExhibitionCusInfo> getExhibitionCustomMap(String exhibitionId) {
        Map<String, ExhibitionCusInfo> map = new HashMap<>();
        exhibitionDao.getExhibitionCustomList(exhibitionId).forEach(jsonObject -> {
            statisticsDeposit(map, jsonObject);
        });

        return map;
    }

    private void statisticsDeposit(Map<String, ExhibitionCusInfo> map, JSONObject jsonObject) {
        ExhibitionCusInfo exhibitionCusInfo;
        String regionId = jsonObject.get("regionId").toString();
        String depositStatus = jsonObject.get("DEPOSIT_STATUS").toString();
        Integer participationNum = Integer.parseInt(jsonObject.get("PARTICIPATION_NUM").toString() == "" ? "0" : jsonObject.get("PARTICIPATION_NUM").toString());
        if (map.containsKey(regionId))
            exhibitionCusInfo = map.get(regionId);
        else {
            exhibitionCusInfo = new ExhibitionCusInfo();
            exhibitionCusInfo.setRegionId(regionId);
            exhibitionCusInfo.setDeposit1(0);
            exhibitionCusInfo.setDeposit2(0);
            exhibitionCusInfo.setDeposit3(0);
            exhibitionCusInfo.setDeposit4(0);
            exhibitionCusInfo.setParticipationNum(0);
            map.put(regionId, exhibitionCusInfo);
        }
        exhibitionCusInfo.setParticipationNum(exhibitionCusInfo.getParticipationNum() + participationNum);

        if (depositStatus.equals("1"))
            exhibitionCusInfo.setDeposit1(exhibitionCusInfo.getDeposit1() + 1);
        else if (depositStatus.equals("2"))
            exhibitionCusInfo.setDeposit2(exhibitionCusInfo.getDeposit2() + 1);
        else if (depositStatus.equals("3"))
            exhibitionCusInfo.setDeposit3(exhibitionCusInfo.getDeposit3() + 1);
        else if (depositStatus.equals("4"))
            exhibitionCusInfo.setDeposit4(exhibitionCusInfo.getDeposit4() + 1);
    }

    @Override
    public List<JSONObject> getExhibitionListByCompany(String companyId) {
        List<JSONObject> exhibitionList = exhibitionDao.getExhibitionListByCompany(companyId);
        exhibitionList.forEach(e -> {
            String exhibitionDate = e.get("EXHIBITION_DATE").toString();
            e.put("exDateSort", fmtExhibitionDate(exhibitionDate));
        });
        exhibitionList.sort((s1, s2) -> Integer.parseInt(s1.get("exDateSort").toString()) - (Integer.parseInt(s2.get("exDateSort").toString())));
        return exhibitionList;
    }

    @Override
    public JSONObject getExhibitionById(String id) {
        List<JSONObject> jsonObjectList = exhibitionDao.getExhibitionById(id);
        if (jsonObjectList != null && jsonObjectList.size() > 0)
            return jsonObjectList.get(0);
        else
            return null;
    }

    @Override
    public List<JSONObject> getExhibitionIdByUserId(String userId) {
        JSONObject userJSON = userDao.getViewJSONById(userId);

        Boolean isGroupUsers = false;
        if (userJSON != null && userJSON.get("companyId").equals("201712161613432EAF27DBCCB7D0E6CA"))
            isGroupUsers = true;

        List<JSONObject> exhibitionList = exhibitionDao.getExhibitionIdByUserId(userId, isGroupUsers);
        return exhibitionList;
    }

    public List<JSONObject> getExhibitionSummary() {
        List<JSONObject> summaryArrayList = new ArrayList<>();
        String strCondition = " AND DEL_FLAG=0 ORDER BY SORT_NO ";
        List<CompanyEntity> jsonCompany = companyDao.getByCondition(strCondition, null);
        List<JSONObject> jsonExihibition = exhibitionDao.getExhibitionList();

        Map<String, String> map = new HashMap<>();
        map.put("1", "大型");
        map.put("2", "中型");
        map.put("3", "特种行业");

        CompanyEntity companyInfo = new CompanyEntity();
        companyInfo.setId("0");
        companyInfo.setName("类型");
        jsonCompany.add(0, companyInfo);


        for (Map.Entry<String, String> entry : map.entrySet()) {
            Integer[] ii = {0};
            JSONObject[] typeSummary = {new JSONObject()};
            jsonCompany.forEach((CompanyEntity companyEntity) -> {
                JSONObject exhibitionSummary = new JSONObject();
                if (ii[0] == 0) {
                    exhibitionSummary.put("companyId", "0");
                    exhibitionSummary.put("companyName", "");
                    exhibitionSummary.put("exhibitionType", entry.getKey());
                    exhibitionSummary.put("exhibitionTypeName", entry.getValue() + "汇总");
                } else {
                    exhibitionSummary.put("companyId", companyEntity.getId());
                    exhibitionSummary.put("companyName", companyEntity.getName());
                    exhibitionSummary.put("exhibitionType", entry.getKey());
                    exhibitionSummary.put("exhibitionTypeName", entry.getValue());
                }
                exhibitionSummary.put("total", 0);
                for (int i = 1; i < 13; i++) {
                    exhibitionSummary.put("month" + i, 0);
                }

                if (ii[0] == 0)
                    typeSummary[0] = exhibitionSummary;
                summaryArrayList.add(exhibitionSummary);
                ii[0] = ii[0] + 1;
            });

            jsonExihibition.forEach(json -> {
                String companyId = json.get("COMPANY_ID").toString();
                String exhibitionDate = json.get("EXHIBITION_DATE").toString();
                String type = json.get("TYPE").toString();
                if (type.equals(entry.getKey())) {
                    List<JSONObject> summaryResult = summaryArrayList.stream().filter(exhibitionSummary -> exhibitionSummary.get("companyId").equals(companyId) && exhibitionSummary.get("exhibitionType").equals(type)).collect(Collectors.toList());
                    if (summaryResult.size() > 0) {
                        String[] dataArr = exhibitionDate.split("-");
                        Integer month = 0;
                        if (dataArr.length >= 2) {
                            month = Integer.parseInt(dataArr[1]);
                            JSONObject exhibitionSummary = summaryResult.get(0);
                            Integer monthCount = Integer.parseInt(exhibitionSummary.get("month" + month).toString());
                            exhibitionSummary.put("month" + month, monthCount + 1);

                            Integer total = Integer.parseInt(exhibitionSummary.get("total").toString());
                            exhibitionSummary.put("total", total + 1);

                            Integer typeMonthCount = Integer.parseInt(typeSummary[0].get("month" + month).toString());
                            typeSummary[0].put("month" + month, typeMonthCount + 1);

                            Integer totalType = Integer.parseInt(typeSummary[0].get("total").toString());
                            typeSummary[0].put("total", totalType + 1);
                        }
                    }
                }
            });
        }
        return summaryArrayList;
    }

    @Override
    public List<JSONObject> getNomanagerRegion(String userId) {
        return exhibitionDao.getNomanagerRegion(userId);
    }

    @Override
    public JSONObject getBigCusDepart(String companyId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("bigCusDepart", exhibitionDao.getBigCusDepart(companyId));
        jsonObject.put("bigCusReginon", exhibitionDao.getBigCusRegion(companyId));
        return jsonObject;
    }

    @Override
    public List<JSONObject> getCompanyExhibitionCount() {
        return exhibitionDao.getCompanyExhibitionCount();
    }

}
